package com.guard.agent;

import java.lang.instrument.Instrumentation;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class GuardAgent {

    private static final String BOOTSTRAP_CLASS = "com.guard.agent.Bootstrap";

    private static final String BOOTSTRAP_METHOD = "main";

    /**
     * Agent执行入口
     */
    public static void premain(String args, Instrumentation inst) {
        // guard-boot.jar
        // -- agent/guard-core.jar
        // -- config/agent.properties
        // -- log/guard.log

        //String bootPath = GuardAgent.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        //File agentDirFile = new File(bootPath, "agent");
        //FileUtil.del(agentDirFile);

        // 重新下载core.jar
        // File coreFile = new File(bootPath, "agent/guard-core.jar");
        // HttpUtil.downloadFile("", coreFile);

        // 本地自测
        // File coreFile = new File("/Users/shangwq/Documents/workspace/service-guard/guard-agent/core/target/agent-core-1.0.0-shade.jar");

        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        try {
            ClassLoader agentClassLoader = new URLClassLoader(new URL[] { new URL("file:/Users/shangwq/Documents/workspace/service-guard/guard-agent/core/target/guard-core.jar") }, null);
            Thread.currentThread().setContextClassLoader(agentClassLoader);

            // 反射调用main方法
            agentClassLoader.loadClass(BOOTSTRAP_CLASS)
                    .getMethod(BOOTSTRAP_METHOD, String.class, Instrumentation.class)
                    .invoke(null, args, inst);
        } catch (Throwable t) {
            System.err.println("GuardAgent bootstrap failure.");
            t.printStackTrace();
        } finally {
            Thread.currentThread().setContextClassLoader(cl);
        }
    }

}
